import { defineStore } from "pinia"
import { login as loginApi, register as registerApi,getPerms } from "@/api/loginApi"

export const useLoginStore = defineStore("login", {
  persist: {
    key: "userToken"
  },
  state: () => ({
    token: null as string | null,
    user: null as string | null,
    role: null as string | null,
    expire: null as string | null,
    perms: [] as string[]
  }),
  getters: {
    //检测令牌是否过期
    isExpired(state): boolean {
      let time = new Date(state.expire!)
      return new Date().getTime() >= time.getTime()
    }
  },
  actions: {
    //是否持有token
    isAuthenticated(): boolean {
      if (this.isExpired) {
        this.removeToken()
        return false
      }
      return this.token !== null
    },
    //设置验证token
    setToken(tokenData: any) {
      this.token = tokenData.token
      const expireDate: Date = new Date()
      expireDate.setDate(expireDate.getDate() + tokenData.validTime)
      this.expire = expireDate.toISOString()
      this.role = tokenData.role
    },
    //移除验证token(登出)
    removeToken() {
      this.token = null
      this.expire = null
      this.user = null
      this.role = null
      this.perms = []
    },
    //发送登录请求
    async requestLogin(userData: any) {
      let res: any
      try {
        res = await loginApi(userData)
      } catch (err: any) {
        console.error(err)
        throw { code: -1, msg: "发生网络请求错误" }
      }
      const status = res.status
      if (status === 200) {
        this.setToken(res.data)
        this.user = userData.username
        this.perms = await getPermissions()
        return
      } else {
        throw { code: status, msg: res.msg }
      }
    },
    //发送注册请求
    async requestRegister(userData: any) {
      let res: any
      try {
        res = await registerApi(userData)
      } catch (error) {
        console.error(error)
        throw { code: -1, msg: "发生网络请求错误" }
      }
      const status = res.status
      if (status === 200) {
        return
      } else {
        throw { code: status, msg: res.msg }
      }
    }
  }
})

async function getPermissions() : Promise<string[]> {
  let res
  try {
    res = await getPerms()
  } catch (error) {
    throw { code: -1, msg: "发生网络请求错误" }
  }
  return res.data
}
